package com.cskaoyan.market.controller;



import com.cskaoyan.market.service.MarketRegionService;
import com.cskaoyan.market.service.MarketRegionServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.MarketRegionVo;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/region/*")
public class AdminRegionController extends HttpServlet {
    private MarketRegionService marketRegionService=new MarketRegionServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/region/", "");
        if ("list".equals(op)){
            list(req,resp);
        }

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //表格查询一次后放入context域中，提高下次查询的效率
        ServletContext servletContext = getServletContext();
        List<MarketRegionVo> marketRegionVoList= (List<MarketRegionVo>) servletContext.getAttribute("region");
        if(marketRegionVoList==null){
            marketRegionVoList=marketRegionService.list();
            servletContext.setAttribute("region",marketRegionVoList);
        }
        Object o = ResponseUtil.okList(marketRegionVoList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }
}

